package app.system.controll;

import app.system.entity.SysUser;
import app.system.service.SysUserService;
import app.utils.Result.AjaxResult;
import com.alibaba.fastjson.JSONObject;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.HashMap;
import java.util.Map;
@RestController
public class SysUserControll {
    @Autowired
    private SysUserService userService;

    @PostMapping("Tologin")
    public AjaxResult login(@RequestBody SysUser sysUser){
        System.out.println(JSONObject.toJSONString(sysUser));
        //1.获取Subject
        Subject subject = SecurityUtils.getSubject();
        //2.封装用户数据
        UsernamePasswordToken token = new UsernamePasswordToken(sysUser.getUser_name(),sysUser.getPassword());
        try{
            //提交登录信息
            subject.login(token);
            Map<String,Object> map = new HashMap<>();
            map.put("token",subject.getSession().getId());
            return AjaxResult.success("登录成功",map);
        }catch (UnknownAccountException e){
            return AjaxResult.error(-1,"登录失败，用户名不存在");
        }catch (IncorrectCredentialsException e){
            return AjaxResult.error(-1,"登录失败，密码错误");
        }
    }

    @PostMapping("Toregister")
    public AjaxResult register(@RequestBody SysUser sysUser){
        int code = userService.saveUser(sysUser);
        if (code == -1){
            return AjaxResult.success("用户名已被注册");
        }
        if (code == -2){
            return AjaxResult.success("邮箱已被注册");
        }
        return AjaxResult.success("注册成功");
    }

    /**
     * 判断用户是否登录
     * @return
     */
    @GetMapping("IfLogin")
    public int IfLogin(){
        SysUser sysUser = (SysUser) SecurityUtils.getSubject().getPrincipal();
        System.out.println(JSONObject.toJSONString(sysUser));
        if (sysUser == null){
            return -1;
        }else {
            return 0;
        }
    }

    @GetMapping("logout")
    public AjaxResult logout(HttpServletRequest request){
        request.getSession().removeAttribute("user");
        return AjaxResult.success("您已退出登录");
    }
}
